package com.hxx.sbMyBatis.service;

import com.hxx.sbMyBatis.config.springtransaction.TransactionEngine;
import com.hxx.sbMyBatis.config.springtransaction.TransactionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class OrderService {

    @Autowired
    private TransactionEngine transactionEngine;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 示例1：基本使用
     */
    public void processSimpleOrder() {
        // 注册多个数据库操作
        transactionEngine.register(() -> {
            jdbcTemplate.update("INSERT INTO orders(id, user_id, amount) VALUES(?, ?, ?)",
                    "ORDER_001", "USER_001", 100.0);
        });

        transactionEngine.register(() -> {
            jdbcTemplate.update("UPDATE inventory SET stock = stock - ? WHERE product_id = ?",
                    1, "PRODUCT_001");
        });

        // 统一提交
        transactionEngine.persistence();
        System.out.println("事务执行完成，操作数量: " + transactionEngine.getRegisteredOperationCount());
    }

    /**
     * 示例2：批量注册操作
     */
    public void processBatchOrders() {
        List<Runnable> batchOperations = Arrays.asList(
                () -> jdbcTemplate.update("INSERT INTO orders(id, user_id) VALUES(?, ?)",
                        "ORDER_002", "USER_002"),
                () -> jdbcTemplate.update("INSERT INTO orders(id, user_id) VALUES(?, ?)",
                        "ORDER_003", "USER_003"),
                () -> jdbcTemplate.update("UPDATE user SET order_count = order_count + 1 WHERE id = ?",
                        "USER_002")
        );

        // 批量注册
        transactionEngine.register(batchOperations);

        // 再单独注册一个操作
        transactionEngine.register(() -> {
            jdbcTemplate.update("UPDATE statistics SET total_orders = total_orders + ?", 2);
        });

        // 统一提交
        transactionEngine.persistence();
    }

    /**
     * 示例3：复杂业务逻辑
     */
    public void processComplexBusiness() {
        String orderId = "ORDER_COMPLEX_001";
        String userId = "USER_COMPLEX_001";

        // 注册多个相关操作
        transactionEngine.register(() -> {
            // 创建订单
            jdbcTemplate.update(
                    "INSERT INTO orders(id, user_id, status, amount) VALUES(?, ?, ?, ?)",
                    orderId, userId, "CREATED", 200.0
            );
        });

        transactionEngine.register(() -> {
            // 扣减库存
            jdbcTemplate.update(
                    "UPDATE inventory SET stock = stock - ?, locked_stock = locked_stock - ? WHERE product_id = ?",
                    2, 2, "PRODUCT_002"
            );
        });

        transactionEngine.register(() -> {
            // 更新用户订单统计
            jdbcTemplate.update(
                    "UPDATE user SET total_amount = total_amount + ?, last_order_time = NOW() WHERE id = ?",
                    200.0, userId
            );
        });

        transactionEngine.register(() -> {
            // 记录审计日志
            jdbcTemplate.update(
                    "INSERT INTO audit_log(order_id, action, operator) VALUES(?, ?, ?)",
                    orderId, "ORDER_CREATED", "SYSTEM"
            );
        });

        try {
            transactionEngine.persistence();
            System.out.println("复杂业务事务执行成功");
        } catch (TransactionException e) {
            System.err.println("事务执行失败: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 示例4：异常处理场景
     */
    public void processOrderWithException() {
        transactionEngine.register(() -> {
            jdbcTemplate.update("INSERT INTO orders(id, user_id) VALUES(?, ?)",
                    "ORDER_EXCEPTION", "USER_EXCEPTION");
        });

        // 这个操作会抛出异常
        transactionEngine.register(() -> {
            // 模拟业务异常
            throw new RuntimeException("模拟业务异常");
        });

        transactionEngine.register(() -> {
            jdbcTemplate.update("UPDATE inventory SET stock = stock - ?", 1);
        });

        try {
            transactionEngine.persistence();
        } catch (TransactionException e) {
            System.out.println("事务已回滚，所有操作都不会生效");
            // 这里可以进行异常处理或重试逻辑
        }
    }
}
